<template>
  <div>
    <h2 class="title">区域路向占比:</h2>
    <div class="HBox">
      <input class="search-input" type="text" v-model="searchQuery" @keydown.enter="handleSearch" :placeholder="placeholder" />
      <button :class="{Button: true, search: searching}" @click="handleSearch">查询</button>
    </div>
    <ul class="province-list">
      <li :class="{province: true, extend: expandedProvinces.includes(province.code)}"
      v-for="province in provinces" :key="province.code" 
      :data-province-code="province.code" @click="toggleCities(province.code)">
        <span>
          <FontAwesomeIcon 
            :icon="expandedProvinces.includes(province.code) ? 'chevron-down' : 'chevron-right'"
          />
          {{ province.name }} - {{ province.percentage }}%
        </span>
        <ul class="city-list" v-if="expandedProvinces.includes(province.code)">
          <li :class="{city: true, extend: expandedProvinces.includes(province.code)}" 
          v-for="city in cities[province.code]" :key="city.code" 
          :data-city-code="city.code" @click.stop="handleCityClick(city)">
            {{ city.name }} - {{ city.percentage }}%
          </li>
        </ul>
      </li>
    </ul>
  </div>
</template>

<script>
import { getProvinces, getCitiesByProvince, searchRegion } from '@/utils/dataService.js';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'

export default {
  component: {
    FontAwesomeIcon,
  },
  props: ['data', 'type'],
  data() {
    return {
      provinces: [],
      cities: {},
      expandedProvinces: [],
      searchQuery: '',
      placeholder: '请输入区域名称搜索...',
      searching: false,
    };
  },
  watch: {
    data: {
      immediate: true,
      handler(newData) {
        this.provinces = getProvinces(newData);
      }
    }
  },
  methods: {
    handleSearch() {
      this.searching=true;
      this.$forceUpdate();
      setTimeout(() => {
        this.searching=false;
      }, 200);
      
      if (!this.searchQuery.trim()) {
        this.placeholder = '请输入区域名称搜索...';
        return;
      }
      const result = searchRegion(this.data, this.searchQuery);
      console.log(`搜索区域: ${this.searchQuery}`);
      // console.log(`原始数据: `, this.data, this.provinces, this.cities);

      if (result.length > 0) {
        console.log(`搜索成功: `, result);
        // 存储所有搜索到的省份和城市的 DOM 元素
        const resultElements = [];

        result.forEach(item => {
          const isProvince = item.code === item.par_code;
          const code = item.code;
          // 展开搜索结果
          if (!this.expandedProvinces.includes(item.par_code)) {
            this.toggleCities(item.par_code);
          }
          // 无论是否是省份，都记录下来，用于后续查找 DOM
          resultElements.push({ isProvince, code });
        });
        this.placeholder = '请输入区域名称搜索...';

        this.$nextTick(() => {
          const matchedEls = [];
          // 遍历所有搜索结果，找到对应的 DOM 元素
          resultElements.forEach(({ isProvince, code }) => {
            if (isProvince) {
              // 查找省份的 DOM
              const provinceEl = document.querySelector(`[data-province-code="${code}"]`);
              if (provinceEl) matchedEls.push(provinceEl);
            } else {
              // 查找城市的 DOM
              const cityEl = document.querySelector(`[data-city-code="${code}"]`);
              if (cityEl) matchedEls.push(cityEl);
            }
          });

          if (matchedEls.length > 0) {
            // 滚动到第一个结果
            matchedEls[0].scrollIntoView({
              behavior: 'smooth',
              block: 'center'
            });

            // 给所有匹配项添加闪烁动画
            matchedEls.forEach(el => {
              el.classList.add('blink');
            });
            // 3秒后移除闪烁类
            setTimeout(() => {
              matchedEls.forEach(el => {
                el.classList.remove('blink');
              });
            }, 10000);
          }
        });
      } else {
        // 清空搜索栏并在搜索栏中显示搜索失败信息
        console.log(`搜索失败: ${this.searchQuery}`);
        this.searchQuery = '';
        this.placeholder = '搜索失败，请重新搜索';
      }
    },
    handleCityClick(city) {
      console.log(`选择城市: ${city.name}`);
      let cityEl= document.querySelector(`[data-city-code="${city.code}"]`);
      if(cityEl.classList.contains('blink')) {
        cityEl.classList.remove('blink');
      } 
      // else {
      //   cityEl.classList.add('blink');
      // }
    },
    toggleCities(provinceCode) {
      if (this.expandedProvinces.includes(provinceCode)) {
        this.expandedProvinces = this.expandedProvinces.filter(c => c !== provinceCode);
      } else {
        this.expandedProvinces.push(provinceCode);
        this.cities[provinceCode] = getCitiesByProvince(this.data, provinceCode);
      }
    }
  }
};
</script>